package com.example.demo.file;

import com.example.demo.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
@RequestMapping("upload")
public class FileController {

    public static final String ROOT = "upload-dir";

    @Autowired
    private  ResourceLoader resourceLoader;
//    /**
//     * 文件上传具体实现方法（单文件上传）
//     *
//     * @param file
//     * @return
//     * @create 2017年3月11日
//     */
//    @RequestMapping(value = "/upload", method = RequestMethod.POST)
//    @ResponseBody
//    public String upload(@RequestParam("file") MultipartFile file) {
//        if (!file.isEmpty()) {
//            try {
//                // 这里只是简单例子，文件直接输出到项目路径下。
//                // 实际项目中，文件需要输出到指定位置，需要在增加代码处理。
//                // 还有关于文件格式限制、文件大小限制，详见：中配置。
//                BufferedOutputStream out = new BufferedOutputStream(
//                        new FileOutputStream(new File(file.getOriginalFilename())));
//                out.write(file.getBytes());
//                out.flush();
//                out.close();
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//                return "上传失败," + e.getMessage();
//            } catch (IOException e) {
//                e.printStackTrace();
//                return "上传失败," + e.getMessage();
//            }
//            return "上传成功";
//        } else {
//            return "上传失败，因为文件是空的.";
//        }
//    }

    @RequestMapping(value = "simupload", method = RequestMethod.POST)
    @ResponseBody
    public String Simditorploadfile(MultipartHttpServletRequest request, HttpServletRequest httpServletRequest) {
        System.out.println("--------收到上传");
        String imgurl = "";

        MultipartFile multipartFile = request.getFile("file");

        try {
            Path rootPaths = Paths.get(ROOT);
            String filepath = multipartFile.getOriginalFilename();
            int idx = filepath.lastIndexOf(".");
            //文件后缀
            String extention = filepath.substring(idx);
            if (!Files.exists(rootPaths)) {
                Files.createDirectories(rootPaths);
            }



            Path imageFilePath =  Paths.get(ROOT, Utils.rename() + extention);
//            Files.createFile(imageFilePath);
            Files.copy(multipartFile.getInputStream(),imageFilePath);

            imgurl = imageFilePath.getFileName().toString();
            System.out.println("上传成功");
            return "{\"success\":\"" + true + "\",\"file_path\":\"" + imgurl + "\"}";
        } catch (Exception e) {
            System.out.println(e);
            return "{\"success\":\"" + false + "\",\"file_path\":\"" + imgurl + "\"}";
        }
    }




    @RequestMapping(method = RequestMethod.GET, value = "/{filename:.+}")
    @ResponseBody
    public ResponseEntity<?> getFile(@PathVariable String filename) {
        try {
            return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(ROOT, filename).toString()));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }

}
